import { defineStore } from 'pinia';
import { ref } from 'vue';

const LOCAL_STORAGE_KEY = 'axiom-view-theme';

// Helper function to apply the theme class to the document element
const applyTheme = (themeName) => {
  if (typeof document !== 'undefined') {
    const root = document.documentElement;

    // Set the data-theme attribute for specific theme styles
    root.setAttribute('data-theme', themeName);

    // Determine and set the color scheme (dark or light)
    const isDark = themeName.includes('dark') || themeName.includes('cyber') || themeName.includes('neon');
    root.setAttribute('data-scheme', isDark ? 'dark' : 'light');

    // For backward compatibility or specific component styling, we can still use classes
    const themeClasses = ['dark', 'light', 'neon', 'cyberpunk', 'ocean', 'high-contrast', 'rainbow-cyber'];
    themeClasses.forEach(t => root.classList.remove(`theme-${t}`));
    if (themeName && themeName !== 'default') {
      root.classList.add(`theme-${themeName}`);
    }
  }
};

// This function is run once when the module is first imported.
const getInitialTheme = () => {
  if (typeof window !== 'undefined') {
    const savedTheme = localStorage.getItem(LOCAL_STORAGE_KEY) || 'light';
    applyTheme(savedTheme);
    return savedTheme;
  }
  return 'light'; // Default for SSR or environments without localStorage
};

// Initialize the theme as soon as the app loads, before Vue mounts.
const initialTheme = getInitialTheme();

export const useThemeStore = defineStore('theme', () => {
  const theme = ref(initialTheme);
  const themes = ref([
    { label: '默认', value: 'default' },
    { label: '浅色', value: 'light' },
    { label: '深色', value: 'dark' },
    { label: '赛博朋克', value: 'cyberpunk' },
    { label: '海洋', value: 'ocean' },
    { label: '霓虹', value: 'neon' },
    { label: '彩虹赛博', value: 'rainbow-cyber' },
    { label: '高对比度', value: 'high-contrast' }
  ]);

  const setTheme = (newTheme) => {
    theme.value = newTheme;
    if (typeof window !== 'undefined') {
      localStorage.setItem(LOCAL_STORAGE_KEY, newTheme);
      applyTheme(newTheme);
    }
  };

  return {
    theme,
    themes,
    setTheme,
  };
}); 